package org.dwpd.service.inbox.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.dwpd.mapper.inbox.InBoxMapper;
import org.dwpd.domain.message.HistoryMessage;
import org.dwpd.domain.message.MessageInfo;
import org.dwpd.domain.common.Result;
import org.dwpd.domain.user.UserDTO;
import org.dwpd.service.inbox.InBoxService;
import org.dwpd.service.message.MessageService;
import org.dwpd.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static org.dwpd.utils.RedisConstants.INBOX_USER_KEY;

@Slf4j
@Service
public class InBoxServiceImpl extends ServiceImpl<InBoxMapper, HistoryMessage> implements InBoxService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MessageService messageService;

    @Override
    public Result getHistoryMessageForSelf() {
        // 判断用户是否登录
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return Result.unlogin(-2, "用户未登录");
        }
        Integer userId = user.getUserId();
        log.info("用户-{}: 获取收集箱信息", userId);
        List<HistoryMessage> historyMessages = query().eq("accept_user_id", userId).orderByDesc("create_time").list();
        if (historyMessages.isEmpty()) {
            return Result.fail(-1, "获取历史信息失败");
        }
        return Result.success(historyMessages);
    }

    @Override
    public Result getOnSeatMessageForSelf() {
        // 1. 判断用户是否登录
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return Result.unlogin(-2, "用户未登录");
        }
        Integer userId = user.getUserId();
        log.info("用户-{}: 获取所有参与任务的用户帖信息", userId);
        // 2. 查询收件箱 ZREVRANGEBYSCORE key Max Min limit offset count
        Long size = stringRedisTemplate.opsForZSet().size(INBOX_USER_KEY + userId);
        // 非空判断
        if (size == null || size <= 0) {
            return Result.success(Collections.emptyList());
        }
        Set<String> sets = stringRedisTemplate.opsForZSet().reverseRange(INBOX_USER_KEY + userId, 0, size + 1);
        List<Integer> ids = sets.stream().map(Integer::valueOf).collect(Collectors.toList());
        // 3. 返回ids查询结果并返回
        List<MessageInfo> messageInfos = messageService.getMessageByIds(ids);
        return Result.success(messageInfos);
    }
}
